package cn.zly.spring.beans.factory.support;
import cn.zly.spring.beans.factory.BeanFactory;
import cn.zly.spring.beans.factory.BeansException;
import cn.zly.spring.beans.factory.config.BeanDefinition;
import cn.zly.spring.beans.factory.config.BeanPostProcessor;
import cn.zly.spring.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanglianyong
 * @date 2024/12/26
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {


	private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
	@Override
	public Object getBean(String beanName) {
		Object bean = getSingleton(beanName);
		if (bean != null) {
			return bean;
		}
		return createBean(beanName, getBeanDefinition(beanName), new Object[]{});
	}


	@Override
	public Object getBean(String beanName, Object... args) throws BeansException {
		Object bean = getSingleton(beanName);
		if (bean != null) {
			return bean;
		}
		return createBean(beanName, getBeanDefinition(beanName), args);
	}


	@Override
	public Object getBean(String beanName, Class<?> requireType) throws BeansException {
		Object bean = getSingleton(beanName);
		if (bean != null) {
			return bean;
		}
		return createBean(beanName, getBeanDefinition(beanName), new Object[]{});
	}

	public List<BeanPostProcessor> getBeanPostProcessors() {
		return this.beanPostProcessors;
	}

	@Override
	public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
		this.beanPostProcessors.remove(beanPostProcessor);
		this.beanPostProcessors.add(beanPostProcessor);
	}

	protected abstract BeanDefinition getBeanDefinition(String beanName);

	protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args);
}
